<script setup>
import { useRouter } from 'vue-router';
import { ref, reactive } from 'vue'
import { useStore } from 'vuex'
import request from '@/utils/request'
import { login } from '@/api/index'

const ruleFormRef = ref()
const router = useRouter();
const store = useStore();
const ruleForm = reactive({
  userName: localStorage['userName'] || 'admin',
  userPwd: localStorage['userPwd'] || '123456',
})

const rules = reactive({
  userName: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { min: 1, max: 32, message: '账号最少8位, 最长32位', trigger: 'blur' },
  ],
  userPwd: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
    { min: 1, max: 32, message: '密码最少8位, 最长32位', trigger: 'blur' },
  ]
})


const doLogin = async (fromEml) => {
  fromEml.validate(async (valid, fields) => {
    if (valid) {
      try {
        let userInfo = await login({
          userName: ruleForm.userName,
          userPwd: ruleForm.userPwd
        })
        
        localStorage['userName'] = ruleForm.userName
        localStorage['userPwd'] = ruleForm.userPwd
        console.log(userInfo)
        router.push('/welcome')
        store.commit('saveUserInfo', userInfo)
      } catch (error) {
        console.error('登陆失败', error)
      }
    } else {
      console.log('error', fields)
    }
  })
}

</script>
<template>
  <div class="login-wrapper">
    <div class="modal">
      <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules">
        <div class="title">Title</div>
        <el-form-item prop="userName">
          <el-input type="text" v-model="ruleForm.userName" @keyup.enter="doLogin(ruleFormRef)">
            <template #prepend>
              <el-icon>
                <User />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="userPwd">
          <el-input type="password" v-model="ruleForm.userPwd" @keyup.enter="doLogin(ruleFormRef)">
            <template #prepend>
              <el-icon>
                <Lock />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="doLogin(ruleFormRef)" type="primary" class="btn-login">登陆</el-button>
        </el-form-item>
      </el-form>
      <!-- <h1>login</h1>
      <el-button @click="doLogin">登录</el-button>
      <el-button @click="router.push('/')">首页</el-button>
      <router-link to="/">首页</router-link> -->
    </div>
  </div>
</template>

<style lang="scss">
.login-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  background: #f9fcff;
  width: 100vw;
  height: 100vh;

  .modal {
    width: 500px;
    padding: 50px;
    background: #fff;
    border-radius: 5px;
    box-shadow: 0 0 5px #ccc;

    .title {
      font-size: 40px;
      text-align: center;
      line-height: 1.5;
      margin-bottom: 30px;
    }

    .btn-login {
      width: 100%;
    }
  }
}
</style>